package com.controller;

import com.util.FileUtil;
import com.util.MD5Util;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Controller
public class ImgController {
    /**
     * 文件上传
     *
     * @param imgFile
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/uploadImg")
    public String uploadImg(MultipartFile imgFile, HttpSession session, Model model) {
        //获取上传文件的文件名字
        String filename = imgFile.getOriginalFilename();
        System.out.println(filename);
        //文件名去后缀
        String substring = filename.substring(0, filename.lastIndexOf(".jpg"));
        System.out.println(substring);
        //加密加后缀
        String s = new StringBuffer(MD5Util.EncoderByMd5(substring)).append(".jpg").toString();
        //获取保存文件的目录
        String path = session.getServletContext().getRealPath("/WEB-INF/img");
        System.out.println(path);

        //创建目录
        FileUtil.createDir(path);

        //文件保存路径
        File outFile = new File(path, s);

        model.addAttribute("img", s);
        try {
            imgFile.transferTo(outFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "index";
    }
}
